{% extends 'base.html' %}
{% load static %}

{% block title %}系统设置 - CFS Web System{% endblock %}

{% block page_type %}settings{% endblock %}

{% block breadcrumb_items %}
<li class="breadcrumb-item"><a href="{% url 'dashboard:dashboard' %}">仪表板</a></li>
<li class="breadcrumb-item active">系统设置</li>
{% endblock %}

{% block content %}
<div class="row">
    <!-- 设置导航 -->
    <div class="col-lg-3">
        <div class="card">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-cog me-2"></i>设置分类
                </h6>
            </div>
            <div class="list-group list-group-flush">
                <a href="#general" class="list-group-item list-group-item-action active" data-bs-toggle="pill">
                    <i class="fas fa-sliders-h me-2"></i>常规设置
                </a>
                <a href="#file" class="list-group-item list-group-item-action" data-bs-toggle="pill">
                    <i class="fas fa-file-alt me-2"></i>文件设置
                </a>
                <a href="#processing" class="list-group-item list-group-item-action" data-bs-toggle="pill">
                    <i class="fas fa-cogs me-2"></i>处理设置
                </a>
                <a href="#notification" class="list-group-item list-group-item-action" data-bs-toggle="pill">
                    <i class="fas fa-bell me-2"></i>通知设置
                </a>
                <a href="#security" class="list-group-item list-group-item-action" data-bs-toggle="pill">
                    <i class="fas fa-shield-alt me-2"></i>安全设置
                </a>
                <a href="#backup" class="list-group-item list-group-item-action" data-bs-toggle="pill">
                    <i class="fas fa-database me-2"></i>备份设置
                </a>
                <a href="#advanced" class="list-group-item list-group-item-action" data-bs-toggle="pill">
                    <i class="fas fa-code me-2"></i>高级设置
                </a>
            </div>
        </div>
        
        <!-- 快速操作 -->
        <div class="card mt-3">
            <div class="card-header">
                <h6 class="mb-0">
                    <i class="fas fa-bolt me-2"></i>快速操作
                </h6>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <button type="button" class="btn btn-outline-primary" onclick="exportSettings()">
                        <i class="fas fa-download"></i> 导出设置
                    </button>
                    <button type="button" class="btn btn-outline-secondary" onclick="importSettings()">
                        <i class="fas fa-upload"></i> 导入设置
                    </button>
                    <button type="button" class="btn btn-outline-warning" onclick="resetSettings()">
                        <i class="fas fa-undo"></i> 重置设置
                    </button>
                    <button type="button" class="btn btn-outline-info" onclick="testConnection()">
                        <i class="fas fa-wifi"></i> 测试连接
                    </button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 设置内容 -->
    <div class="col-lg-9">
        <form id="settings-form">
            <div class="tab-content">
                <!-- 常规设置 -->
                <div class="tab-pane fade show active" id="general">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-sliders-h me-2"></i>常规设置
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">系统名称</label>
                                    <input type="text" class="form-control" name="system_name" value="CFS Web System">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">系统版本</label>
                                    <input type="text" class="form-control" name="system_version" value="1.0.0" readonly>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">默认语言</label>
                                    <select class="form-select" name="default_language">
                                        <option value="zh-cn" selected>简体中文</option>
                                        <option value="en">English</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">时区</label>
                                    <select class="form-select" name="timezone">
                                        <option value="Asia/Shanghai" selected>Asia/Shanghai</option>
                                        <option value="UTC">UTC</option>
                                        <option value="America/New_York">America/New_York</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">日期格式</label>
                                    <select class="form-select" name="date_format">
                                        <option value="YYYY-MM-DD" selected>YYYY-MM-DD</option>
                                        <option value="DD/MM/YYYY">DD/MM/YYYY</option>
                                        <option value="MM/DD/YYYY">MM/DD/YYYY</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">时间格式</label>
                                    <select class="form-select" name="time_format">
                                        <option value="24" selected>24小时制</option>
                                        <option value="12">12小时制</option>
                                    </select>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">系统描述</label>
                                    <textarea class="form-control" name="system_description" rows="3">CFS文件处理系统，提供文件上传、模板配置、数据生成等功能。</textarea>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="debug_mode" id="debug_mode">
                                        <label class="form-check-label" for="debug_mode">
                                            启用调试模式
                                        </label>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="maintenance_mode" id="maintenance_mode">
                                        <label class="form-check-label" for="maintenance_mode">
                                            维护模式
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 文件设置 -->
                <div class="tab-pane fade" id="file">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-file-alt me-2"></i>文件设置
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">最大文件大小 (MB)</label>
                                    <input type="number" class="form-control" name="max_file_size" value="50" min="1" max="1000">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">文件保存天数</label>
                                    <input type="number" class="form-control" name="file_retention_days" value="30" min="1" max="365">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">上传目录</label>
                                    <input type="text" class="form-control" name="upload_directory" value="uploads/">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">输出目录</label>
                                    <input type="text" class="form-control" name="output_directory" value="outputs/">
                                </div>
                                <div class="col-12">
                                    <label class="form-label">允许的文件类型</label>
                                    <div class="row">
                                        <div class="col-md-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="allowed_extensions" value=".xlsx" id="ext_xlsx" checked>
                                                <label class="form-check-label" for="ext_xlsx">.xlsx</label>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="allowed_extensions" value=".xls" id="ext_xls" checked>
                                                <label class="form-check-label" for="ext_xls">.xls</label>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="allowed_extensions" value=".csv" id="ext_csv" checked>
                                                <label class="form-check-label" for="ext_csv">.csv</label>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="allowed_extensions" value=".txt" id="ext_txt">
                                                <label class="form-check-label" for="ext_txt">.txt</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="auto_cleanup" id="auto_cleanup" checked>
                                        <label class="form-check-label" for="auto_cleanup">
                                            自动清理过期文件
                                        </label>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="virus_scan" id="virus_scan">
                                        <label class="form-check-label" for="virus_scan">
                                            启用病毒扫描
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 处理设置 -->
                <div class="tab-pane fade" id="processing">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-cogs me-2"></i>处理设置
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">最大并发任务数</label>
                                    <input type="number" class="form-control" name="max_concurrent_tasks" value="5" min="1" max="20">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">任务超时时间 (分钟)</label>
                                    <input type="number" class="form-control" name="task_timeout" value="30" min="1" max="120">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">重试次数</label>
                                    <input type="number" class="form-control" name="retry_count" value="3" min="0" max="10">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">队列优先级</label>
                                    <select class="form-select" name="queue_priority">
                                        <option value="fifo" selected>先进先出</option>
                                        <option value="lifo">后进先出</option>
                                        <option value="priority">优先级</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">内存限制 (MB)</label>
                                    <input type="number" class="form-control" name="memory_limit" value="512" min="128" max="2048">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">CPU使用率限制 (%)</label>
                                    <input type="number" class="form-control" name="cpu_limit" value="80" min="10" max="100">
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="auto_retry" id="auto_retry" checked>
                                        <label class="form-check-label" for="auto_retry">
                                            自动重试失败任务
                                        </label>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="parallel_processing" id="parallel_processing" checked>
                                        <label class="form-check-label" for="parallel_processing">
                                            启用并行处理
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 通知设置 -->
                <div class="tab-pane fade" id="notification">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-bell me-2"></i>通知设置
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">SMTP服务器</label>
                                    <input type="text" class="form-control" name="smtp_host" placeholder="smtp.example.com">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">SMTP端口</label>
                                    <input type="number" class="form-control" name="smtp_port" value="587" min="1" max="65535">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">发件人邮箱</label>
                                    <input type="email" class="form-control" name="smtp_username" placeholder="noreply@example.com">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">邮箱密码</label>
                                    <input type="password" class="form-control" name="smtp_password" placeholder="••••••••">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">管理员邮箱</label>
                                    <input type="email" class="form-control" name="admin_email" placeholder="admin@example.com">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">通知频率</label>
                                    <select class="form-select" name="notification_frequency">
                                        <option value="immediate" selected>立即</option>
                                        <option value="hourly">每小时</option>
                                        <option value="daily">每日</option>
                                        <option value="weekly">每周</option>
                                    </select>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">通知类型</label>
                                    <div class="row">
                                        <div class="col-md-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="notification_types" value="task_complete" id="notify_complete" checked>
                                                <label class="form-check-label" for="notify_complete">任务完成</label>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="notification_types" value="task_failed" id="notify_failed" checked>
                                                <label class="form-check-label" for="notify_failed">任务失败</label>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="notification_types" value="system_error" id="notify_error" checked>
                                                <label class="form-check-label" for="notify_error">系统错误</label>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="notification_types" value="maintenance" id="notify_maintenance">
                                                <label class="form-check-label" for="notify_maintenance">维护通知</label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="email_notifications" id="email_notifications" checked>
                                        <label class="form-check-label" for="email_notifications">
                                            启用邮件通知
                                        </label>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="browser_notifications" id="browser_notifications" checked>
                                        <label class="form-check-label" for="browser_notifications">
                                            启用浏览器通知
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 安全设置 -->
                <div class="tab-pane fade" id="security">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-shield-alt me-2"></i>安全设置
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">会话超时时间 (分钟)</label>
                                    <input type="number" class="form-control" name="session_timeout" value="30" min="5" max="480">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">最大登录尝试次数</label>
                                    <input type="number" class="form-control" name="max_login_attempts" value="5" min="1" max="20">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">密码最小长度</label>
                                    <input type="number" class="form-control" name="min_password_length" value="8" min="6" max="32">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">锁定时间 (分钟)</label>
                                    <input type="number" class="form-control" name="lockout_duration" value="15" min="1" max="60">
                                </div>
                                <div class="col-12">
                                    <label class="form-label">允许的IP地址 (每行一个)</label>
                                    <textarea class="form-control" name="allowed_ips" rows="3" placeholder="192.168.1.0/24\n10.0.0.0/8"></textarea>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="require_https" id="require_https">
                                        <label class="form-check-label" for="require_https">
                                            强制使用HTTPS
                                        </label>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="enable_2fa" id="enable_2fa">
                                        <label class="form-check-label" for="enable_2fa">
                                            启用双因素认证
                                        </label>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="audit_log" id="audit_log" checked>
                                        <label class="form-check-label" for="audit_log">
                                            启用审计日志
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 备份设置 -->
                <div class="tab-pane fade" id="backup">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-database me-2"></i>备份设置
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">备份频率</label>
                                    <select class="form-select" name="backup_frequency">
                                        <option value="daily" selected>每日</option>
                                        <option value="weekly">每周</option>
                                        <option value="monthly">每月</option>
                                        <option value="manual">手动</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">备份时间</label>
                                    <input type="time" class="form-control" name="backup_time" value="02:00">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">保留备份数量</label>
                                    <input type="number" class="form-control" name="backup_retention" value="7" min="1" max="30">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">备份压缩级别</label>
                                    <select class="form-select" name="backup_compression">
                                        <option value="none">无压缩</option>
                                        <option value="low">低压缩</option>
                                        <option value="medium" selected>中等压缩</option>
                                        <option value="high">高压缩</option>
                                    </select>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">备份目录</label>
                                    <input type="text" class="form-control" name="backup_directory" value="backups/">
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="auto_backup" id="auto_backup" checked>
                                        <label class="form-check-label" for="auto_backup">
                                            启用自动备份
                                        </label>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="backup_verification" id="backup_verification" checked>
                                        <label class="form-check-label" for="backup_verification">
                                            备份完整性验证
                                        </label>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="d-flex gap-2">
                                        <button type="button" class="btn btn-outline-primary" onclick="createBackup()">
                                            <i class="fas fa-save"></i> 立即备份
                                        </button>
                                        <button type="button" class="btn btn-outline-success" onclick="restoreBackup()">
                                            <i class="fas fa-undo"></i> 恢复备份
                                        </button>
                                        <button type="button" class="btn btn-outline-info" onclick="downloadBackup()">
                                            <i class="fas fa-download"></i> 下载备份
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 高级设置 -->
                <div class="tab-pane fade" id="advanced">
                    <div class="card">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-code me-2"></i>高级设置
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">日志级别</label>
                                    <select class="form-select" name="log_level">
                                        <option value="DEBUG">DEBUG</option>
                                        <option value="INFO" selected>INFO</option>
                                        <option value="WARNING">WARNING</option>
                                        <option value="ERROR">ERROR</option>
                                        <option value="CRITICAL">CRITICAL</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">日志保留天数</label>
                                    <input type="number" class="form-control" name="log_retention_days" value="30" min="1" max="365">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">缓存过期时间 (秒)</label>
                                    <input type="number" class="form-control" name="cache_timeout" value="3600" min="60" max="86400">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">API请求限制 (每分钟)</label>
                                    <input type="number" class="form-control" name="api_rate_limit" value="100" min="10" max="1000">
                                </div>
                                <div class="col-12">
                                    <label class="form-label">自定义CSS</label>
                                    <textarea class="form-control" name="custom_css" rows="5" placeholder="/* 自定义样式 */"></textarea>
                                </div>
                                <div class="col-12">
                                    <label class="form-label">自定义JavaScript</label>
                                    <textarea class="form-control" name="custom_js" rows="5" placeholder="// 自定义脚本"></textarea>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="enable_api" id="enable_api" checked>
                                        <label class="form-check-label" for="enable_api">
                                            启用API接口
                                        </label>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="enable_cache" id="enable_cache" checked>
                                        <label class="form-check-label" for="enable_cache">
                                            启用缓存
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 保存按钮 -->
            <div class="card mt-3">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="text-muted">
                            <small>最后更新: <span id="last-updated">{{ settings.updated_at|date:"Y-m-d H:i:s" }}</span></small>
                        </div>
                        <div class="d-flex gap-2">
                            <button type="button" class="btn btn-outline-secondary" onclick="resetForm()">
                                <i class="fas fa-undo"></i> 重置
                            </button>
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> 保存设置
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 导入设置模态框 -->
<div class="modal fade" id="importSettingsModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">导入设置</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">选择设置文件</label>
                    <input type="file" class="form-control" id="settings-file" accept=".json">
                    <div class="form-text">支持JSON格式的设置文件</div>
                </div>
                <div class="mb-3">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="merge-settings" checked>
                        <label class="form-check-label" for="merge-settings">
                            合并设置（保留现有设置）
                        </label>
                    </div>
                </div>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    导入设置将覆盖当前配置，请确保备份现有设置。
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="confirmImportSettings()">
                    <i class="fas fa-upload"></i> 导入
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 恢复备份模态框 -->
<div class="modal fade" id="restoreBackupModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">恢复备份</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">选择备份文件</label>
                    <select class="form-select" id="backup-list">
                        <!-- 备份列表将动态加载 -->
                    </select>
                </div>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    恢复备份将覆盖当前所有数据，此操作不可逆！
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmRestoreBackup()">
                    <i class="fas fa-undo"></i> 恢复
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeSettingsPage();
});

// 初始化设置页面
function initializeSettingsPage() {
    // 加载当前设置
    loadCurrentSettings();
    
    // 绑定表单提交事件
    document.getElementById('settings-form').addEventListener('submit', saveSettings);
    
    // 绑定标签页切换事件
    bindTabEvents();
}

// 绑定标签页事件
function bindTabEvents() {
    const tabLinks = document.querySelectorAll('[data-bs-toggle="pill"]');
    tabLinks.forEach(link => {
        link.addEventListener('shown.bs.tab', function(e) {
            // 标签页切换时的处理
            const targetId = e.target.getAttribute('href').substring(1);
            console.log('切换到标签页:', targetId);
        });
    });
}

// 加载当前设置
function loadCurrentSettings() {
    fetch('/settings/ajax/current/')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            populateForm(data.settings);
        }
    })
    .catch(error => {
        console.error('加载设置失败:', error);
    });
}

// 填充表单
function populateForm(settings) {
    const form = document.getElementById('settings-form');
    
    Object.keys(settings).forEach(key => {
        const element = form.querySelector(`[name="${key}"]`);
        if (element) {
            if (element.type === 'checkbox') {
                element.checked = settings[key];
            } else if (element.type === 'radio') {
                const radio = form.querySelector(`[name="${key}"][value="${settings[key]}"]`);
                if (radio) radio.checked = true;
            } else {
                element.value = settings[key];
            }
        }
    });
}

// 保存设置
function saveSettings(event) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    
    // 处理复选框数组
    const checkboxArrays = ['allowed_extensions', 'notification_types'];
    checkboxArrays.forEach(name => {
        const values = [];
        document.querySelectorAll(`input[name="${name}"]:checked`).forEach(cb => {
            values.push(cb.value);
        });
        formData.delete(name);
        formData.append(name, JSON.stringify(values));
    });
    
    CFS.utils.showLoading(true);
    
    fetch('/settings/ajax/save/', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('设置保存成功', 'success');
            document.getElementById('last-updated').textContent = new Date().toLocaleString('zh-CN');
        } else {
            CFS.utils.showNotification(data.message || '保存失败', 'error');
        }
    })
    .catch(error => {
        console.error('保存设置失败:', error);
        CFS.utils.showNotification('保存设置失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 重置表单
function resetForm() {
    if (confirm('确定要重置所有设置吗？')) {
        loadCurrentSettings();
    }
}

// 导出设置
function exportSettings() {
    window.open('/settings/ajax/export/');
}

// 导入设置
function importSettings() {
    const modal = new bootstrap.Modal(document.getElementById('importSettingsModal'));
    modal.show();
}

// 确认导入设置
function confirmImportSettings() {
    const fileInput = document.getElementById('settings-file');
    const mergeSettings = document.getElementById('merge-settings').checked;
    
    if (!fileInput.files.length) {
        CFS.utils.showNotification('请选择设置文件', 'warning');
        return;
    }
    
    const formData = new FormData();
    formData.append('settings_file', fileInput.files[0]);
    formData.append('merge', mergeSettings);
    
    CFS.utils.showLoading(true);
    
    fetch('/settings/ajax/import/', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('设置导入成功', 'success');
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('importSettingsModal'));
            modal.hide();
            
            // 重新加载设置
            loadCurrentSettings();
        } else {
            CFS.utils.showNotification(data.message || '导入失败', 'error');
        }
    })
    .catch(error => {
        console.error('导入设置失败:', error);
        CFS.utils.showNotification('导入设置失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 重置设置
function resetSettings() {
    if (!confirm('确定要重置所有设置到默认值吗？此操作不可逆！')) {
        return;
    }
    
    CFS.utils.showLoading(true);
    
    fetch('/settings/ajax/reset/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('设置已重置', 'success');
            loadCurrentSettings();
        } else {
            CFS.utils.showNotification(data.message || '重置失败', 'error');
        }
    })
    .catch(error => {
        console.error('重置设置失败:', error);
        CFS.utils.showNotification('重置设置失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 测试连接
function testConnection() {
    CFS.utils.showLoading(true);
    
    fetch('/settings/ajax/test-connection/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('连接测试成功', 'success');
        } else {
            CFS.utils.showNotification(data.message || '连接测试失败', 'error');
        }
    })
    .catch(error => {
        console.error('连接测试失败:', error);
        CFS.utils.showNotification('连接测试失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 创建备份
function createBackup() {
    CFS.utils.showLoading(true);
    
    fetch('/settings/ajax/create-backup/', {
        method: 'POST',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('备份创建成功', 'success');
        } else {
            CFS.utils.showNotification(data.message || '备份创建失败', 'error');
        }
    })
    .catch(error => {
        console.error('创建备份失败:', error);
        CFS.utils.showNotification('创建备份失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 恢复备份
function restoreBackup() {
    // 加载备份列表
    loadBackupList();
    
    const modal = new bootstrap.Modal(document.getElementById('restoreBackupModal'));
    modal.show();
}

// 加载备份列表
function loadBackupList() {
    fetch('/settings/ajax/backup-list/')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            const select = document.getElementById('backup-list');
            select.innerHTML = '';
            
            if (data.backups.length === 0) {
                select.innerHTML = '<option value="">暂无备份文件</option>';
            } else {
                data.backups.forEach(backup => {
                    const option = document.createElement('option');
                    option.value = backup.filename;
                    option.textContent = `${backup.name} (${backup.size}) - ${backup.created_at}`;
                    select.appendChild(option);
                });
            }
        }
    })
    .catch(error => {
        console.error('加载备份列表失败:', error);
    });
}

// 确认恢复备份
function confirmRestoreBackup() {
    const backupFile = document.getElementById('backup-list').value;
    
    if (!backupFile) {
        CFS.utils.showNotification('请选择备份文件', 'warning');
        return;
    }
    
    if (!confirm('确定要恢复此备份吗？当前数据将被覆盖！')) {
        return;
    }
    
    CFS.utils.showLoading(true);
    
    fetch('/settings/ajax/restore-backup/', {
        method: 'POST',
        body: JSON.stringify({ backup_file: backupFile }),
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('备份恢复成功', 'success');
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('restoreBackupModal'));
            modal.hide();
            
            // 重新加载页面
            setTimeout(() => {
                window.location.reload();
            }, 2000);
        } else {
            CFS.utils.showNotification(data.message || '备份恢复失败', 'error');
        }
    })
    .catch(error => {
        console.error('恢复备份失败:', error);
        CFS.utils.showNotification('恢复备份失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 下载备份
function downloadBackup() {
    window.open('/settings/ajax/download-backup/');
}
</script>
{% endblock %}